local hmac = require("eco.hash.hmac")
local sha1 = require("eco.hash.sha1")
print("Content-Type: text/html; charset=UTF-8\r\n")
-- Base32 解码函数
local function base32_decode(str)
    local alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"
    local map = {}
    for i = 1, #alphabet do
        map[alphabet:sub(i,i)] = i-1
    end
    str = str:gsub("=", ""):upper()
    local bits, value, output = 0, 0, {}
    for i = 1, #str do
        local c = str:sub(i,i)
        local v = map[c]
        value = (value << 5) | v
        bits = bits + 5
        if bits >= 8 then
            bits = bits - 8
            table.insert(output, string.char((value >> bits) & 0xFF))
        end
    end
    return table.concat(output)
end
local function totp(secret, digits, period, time)
    digits = digits or 6
    period = period or 30
    time = time or os.time()

    local counter = math.floor(time / period)
    local key = base32_decode(secret)

    local msg = ""
    for i = 7, 0, -1 do
        msg = msg .. string.char((counter >> (i*8)) & 0xFF)
    end

    local ctx = hmac.new(sha1, key)
    ctx:update(msg)
    local hash = ctx:final()

    local offset = string.byte(hash, #hash) & 0x0F
    local binary = ((string.byte(hash, offset+1) & 0x7F) << 24)
                 | ((string.byte(hash, offset+2) & 0xFF) << 16)
                 | ((string.byte(hash, offset+3) & 0xFF) << 8)
                 | (string.byte(hash, offset+4) & 0xFF)

    local otp = binary % (10 ^ digits)
    local code = string.format("%0"..digits.."d", otp)

    -- 计算剩余时间
    local remaining = period - (time % period)

    return code, remaining
end


local tasks = {
    ["aaaa"] = "asdfas",

}

print("<!DOCTYPE html>")
print("<html><head><title>进度列表</title></head><body>")
print("<meta http-equiv='refresh' content='5'>")  -- 每 5 秒刷新一次
print("<h1>任务进度</h1>")
print("<ul>")
for k, v in pairs(tasks) do
    code, remaining = totp(v)
    print("<li>" .. k .. " : " .. code .. "<br>")
    -- 使用 HTML5 progress 标签
    print("<progress value='" .. remaining .. "' max='30'></progress> ")
    print('<button onclick="copyCode(' .. code .. ')">复制</button>')
    print("</li>")
end
print("</ul>")
print([[
<script>
function copyCode(code) {
    navigator.clipboard.writeText(code);
}
</script>
]])

print("</body></html>")


